# -*- coding: utf-8 -*-
from twisted.web import server, resource
from twisted.internet import reactor
from mxit.server.server import *

         
class HttpConnection(ServerConnection):
    queue = []
    
    def __init__(self, userlist):
        super(HttpConnection, self).__init__(None, userlist)
        
    def send_multiple(self, data):
        self.queue += data
        
    def pending(self):
        data = self.queue
        self.queue = []
        return data
        
    
    
class HttpServer(resource.Resource):
    isLeaf = True
    connections = {}
    
    def __init__(self, userlist):
        self.userlist = userlist
        
    def render_GET(self, request):
        args = dict([(key, parse_value(value[0])) for key, value in request.args.items()])
        print args
        id = args['id'][0]
        if id not in self.connections:
            self.connections[id] = HttpConnection(self.userlist)
        
        con = self.connections[id]
        con.got_data(args)
        
        data = con.pending()
        return build_data(data)
        

    def render_POST(self, request):
        return self.render_GET(request)

if __name__ == "__main__":
    userlist = UserList()
    
    
    
    site = server.Site(HttpServer(userlist))
    reactor.listenTCP(8080, site)
    reactor.run()
